//
//  XS_KuaiXueVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/23.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import AliyunPlayer

class XS_discoverQuickLearnM: XS_BaseModel {
    var id = "" //快学编号
    var title = "" //快学标题
    var count = "" //观看人数
    var imgUrl = "" //封面图片地址
    var isCollect = "" //用户是否收藏 yes/no
    var collectCount = 0 //收藏数
}
class XS_queryStarcurriculumDtoM: XS_BaseModel {
    var curriculumImgUrl = "" // 课程图片地址
    var discountPrice = "" // 课程优惠价格
    var price = "" // 课程价格
    var introduce = "" // 课程介绍
    var curriculumName = "" // 课程名称
    var id = 0 // 课程编号
    var isCurriculumSeries = "no"
    var curriculumForm = "online"
}
class XS_queryStarM: XS_BaseModel {
    var curriculumDto = XS_queryStarcurriculumDtoM() // 快学绑定的课程对象
    var isCollect = "" // 是否被收藏 yes/no
    var description = "" // 快学描述
    var curriculumId = 0 // 课程编号
    var count = 0 // 观看人数
    var title = "" // 快学标题
    var videoTime = "" // 快学时长
    var videoUrl = "" // 快学视频ID
    var id = 0 // 快学编号
    var imgUrl = "" // 快学封面图片
}

class XS_KuaiXueVC: XS_BaseVC {
    lazy var loadMoreDisposeBag = DisposeBag()
    lazy var channelArray: [XS_HomeTopM] = []
    lazy var topScroll = UIScrollView()
    lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00)
        lineView.layer.masksToBounds = true
        lineView.layer.cornerRadius = .scale * 1
        return lineView
    }()
    private lazy var currIndex = 0
    private var faxianCollection: UICollectionView!
    
    lazy var faxian = getFaxian()
    lazy var tuijian = getTuijian()
    
    private lazy var page = 0
    private lazy var dataPS = PublishSubject<[XS_discoverQuickLearnM]>()
    private lazy var data: [XS_discoverQuickLearnM] = []
    private lazy var footer = MJRefreshBackNormalFooter()
    private lazy var header = MJRefreshNormalHeader()
    
    private lazy var total = 0
    private lazy var playerData: [XS_queryStarM] = []
    private var playerCollection: UICollectionView!
    var player: AliPlayer?
    
    var selectedTuiJian = true
    
    override func viewWillAppear(_ animated: Bool) {
//        guard XS_Singleton.shared.infoModel != nil else {
//            XS_NVC.shared.toLogin(true)
//            return
//        }
        super.viewWillAppear(animated)
//        self.tabBarController?.tabBar.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.5)
//        self.tabBarController?.tabBar.qmui_backgroundView.isHidden = true
//
//        if selectedTuiJian {
//            changedTabbar(selected: true)
//        } else {
//            changedTabbar(selected: false)
//        }
        if (player == nil) {
            if self.isStatusBarBlack {
                self.page = 0
                self.loadMore(index: self.currIndex)
            } else {
                self.player?.pause()
                self.player = nil
                self.playerData.removeAll()
                self.playerCollection.reloadData()
                self.loadMorePlayer()
            }
        } else {
            if self.isStatusBarBlack {
                player?.pause()
            } else {
                player?.start()
            }
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        self.tabBarController?.tabBar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
//        self.tabBarController?.tabBar.qmui_backgroundView.isHidden = false
//
//        changedTabbar(selected: false)
        
        player?.isAutoPlay = false
        player?.pause()
    }
    
    func changedTabbar(selected: Bool) {
        if selected {
            self.tabBarController?.tabBar.unselectedItemTintColor = UIColor(red: 0.84, green: 0.84, blue: 0.84, alpha: 1.00)
            self.tabBarController?.tabBar.items?[0].image = UIImage(named: "home-5-fill")?.withRenderingMode(.alwaysOriginal)
            self.tabBarController?.tabBar.items?[2].image = UIImage(named: "Icon")?.withRenderingMode(.alwaysOriginal)
            self.tabBarController?.tabBar.items?[3].image = UIImage(named: "Icon_1")?.withRenderingMode(.alwaysOriginal)
        } else {
            self.tabBarController?.tabBar.unselectedItemTintColor = #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1)
            self.tabBarController?.tabBar.items?[0].image = UIImage(named: "icons_Tab Bar_首页备份")?.withRenderingMode(.alwaysOriginal)
            self.tabBarController?.tabBar.items?[2].image = UIImage(named: "icons_Tab Bar_学习")?.withRenderingMode(.alwaysOriginal)
            self.tabBarController?.tabBar.items?[3].image = UIImage(named: "icons_Tab Bar_我的")?.withRenderingMode(.alwaysOriginal)
        }
    }
    
    override func upView() {
        view.addSubview(tuijian)
        tuijian.snp.makeConstraints({$0.edges.equalToSuperview()})
        view.addSubview(faxian)
        faxian.snp.makeConstraints({$0.edges.equalToSuperview()})
        
        let topLayerView = UIView()
        topLayerView.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: .barHeight + 44)
        topLayerView.alpha = 0.5
        topLayerView.backgroundColor = UIColor.gray.withAlphaComponent(0.5)
        topLayerView.layer.borderColor = UIColor.clear.cgColor
        view.addSubview(topLayerView)
        
        let btn = XS_Button()
        btn.setBackgroundImage(UIImage(named: "icon_搜索"), for: .normal)
        view.addSubview(btn)
        btn.snp.makeConstraints {
            $0.width.height.equalTo(24)
            $0.right.equalTo(-16)
            $0.centerY.equalTo(.barHeight + 22)
        }
        btn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                let vc = XS_SearchVC()
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let line = UIView()
        line.layer.cornerRadius = 2
        line.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        line.frame = CGRect(x: .scale*98, y: .barHeight + 41, width: .scale*33, height: 3)
        view.addSubview(line)
        
        let btn1 = XS_Button()
        btn1.setTitle("发现", for: .normal)
        btn1.setTitleColor(#colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), for: .disabled)
        btn1.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        btn1.frame = CGRect(x: .scale*44, y: .barHeight, width: .scale*144, height: 44)
        view.addSubview(btn1)
        let btn2 = XS_Button()
        btn2.setTitle("推荐", for: .normal)
        btn2.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .disabled)
        btn2.setTitleColor(#colorLiteral(red: 0.5333333333, green: 0.5568627451, blue: 0.5764705882, alpha: 1), for: .normal)
        btn2.frame = CGRect(x: .scale*188, y: .barHeight, width: .scale*144, height: 44)
        view.addSubview(btn2)
        
        let btns = [btn1, btn2]
        let observables = btns.map { button in button.rx.tap.map { button } }
        let selected = Observable.from(observables).merge().startWith(btn2)
        for button in btns {
            selected.map ({ item in
                if item == button {
                    line.center.x = button.center.x
                    if button == btn1 {
//                        self.selectedTuiJian = false
//                        self.changedTabbar(selected: false)
                        
                        topLayerView.backgroundColor = UIColor.white
                        //阴影偏移  x，y为正表示向右下偏移
                        btn1.titleLabel?.layer.shadowOffset = CGSize.init(width: 0, height: 0)
                        btn1.titleLabel?.layer.shadowOpacity = 0
                        //阴影偏移  x，y为正表示向右下偏移
                        btn2.titleLabel?.layer.shadowOffset = CGSize.init(width: 0, height: 0)
                        btn2.titleLabel?.layer.shadowOpacity = 0
                        
                        guard XS_Singleton.shared.infoModel != nil else {
                            XS_NVC.shared.toLogin(true)
                            return false
                        }
                        self.faxian.isHidden = false
                        self.tuijian.isHidden = true
                        btn1.titleLabel?.font = .xsFont(name: .semibold, 18)
                        btn2.titleLabel?.font = .xsFont(name: .regular, 18)
                        btn.setBackgroundImage(UIImage(named: "icon_搜索"), for: .normal)
                        self.isStatusBarBlack = true
                        self.player?.pause()
                    } else {
//                        self.selectedTuiJian = true
//                        self.changedTabbar(selected: true)
                        
                        topLayerView.backgroundColor = UIColor.gray.withAlphaComponent(0.5)
                        //阴影偏移  x，y为正表示向右下偏移
                        btn1.titleLabel?.layer.shadowOffset = CGSize.init(width: 1, height: 1)
                        btn1.titleLabel?.layer.shadowOpacity = 0.5
                        //阴影偏移  x，y为正表示向右下偏移
                        btn2.titleLabel?.layer.shadowOffset = CGSize.init(width: 1, height: 1)
                        btn2.titleLabel?.layer.shadowOpacity = 0.5
                        
                        self.faxian.isHidden = true
                        self.tuijian.isHidden = false
                        btn1.titleLabel?.font = .xsFont(name: .regular, 18)
                        btn2.titleLabel?.font = .xsFont(name: .semibold, 18)
                        btn.setBackgroundImage(UIImage(named: "icon_搜索_1"), for: .normal)
                        self.isStatusBarBlack = false
                        self.player?.start()
                    }
                    self.setNeedsStatusBarAppearanceUpdate()
                    return false
                } else {
                    return true
                }
            }).bind(to: button.rx.isEnabled)
            .disposed(by: disposeBag)
        }
    }

    func getFaxian() -> UIView {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view.isHidden = true
        
        let topView = UIView(frame: CGRect.init(x: 0, y: .barHeight + 44, width: view.bounds.width, height: 60))
        view.addSubview(topView)
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: .scale * 166, height: .scale * 166 * (1280 / 720))
        flowLayout.minimumLineSpacing = .scale*12
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: .scale*16, bottom: 0, right: .scale*16)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        view.addSubview(collection)
        collection.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.top.equalTo(topView.snp.bottom)
            $0.bottom.equalTo(-CGFloat.bottomHeight - 49)
        }
        faxianCollection = collection
        
        collection.register(XS_FaxianCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, XS_discoverQuickLearnM>>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_FaxianCell
            cell.modelPS.onNext(it)
            return cell
        })
        
        topScroll.bounces = false
        topScroll.showsHorizontalScrollIndicator = false
        topScroll.clipsToBounds = true
        topScroll.frame = CGRect(x: 0, y: .scale*16, width: topView.bounds.size.width, height: .scale*32)
        topView.addSubview(topScroll)
        topScroll.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(.scale * 29)
            make.height.equalTo(.scale * 3)
            make.width.equalTo(.scale * 20)
            make.centerX.equalTo(-.scale * 20)
        }
//        let btn2 = XS_NoHighlightBtn()
//        btn2.setBackgroundImage(UIImage(named: "icon_12px_添加"), for: .normal)
//        btn2.frame = CGRect(x: .scale*335, y: .scale*18, width: .scale*24, height: .scale*24)
//        topView.addSubview(btn2)
//        btn2.rx.tap.asDriver()
//            .drive(onNext: { [weak self] in
//                guard XS_Singleton.shared.infoModel != nil else {
//                    XS_NVC.shared.toLogin(false)
//                    return
//                }
//                let vc = XS_HangyeVC()
//                vc.tags = (self?.channelArray ?? []).filter { $0.type != "nav" }
//                self?.present(vc, animated: true)
//            }).disposed(by: disposeBag)
        
        XS_Singleton.shared.changeKuaixue = { [weak self] in
            self?.getMenuitemQueryHomeTop()
        }
        XS_Singleton.shared.changeKuaixue?()
        
        dataPS.asDriver(onErrorJustReturn: [])
            .flatMapLatest { Driver.just([SectionModel<String, XS_discoverQuickLearnM>(model: "", items: $0)]) }
            .drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        collection.mj_footer = footer
        footer.rx.refresh
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.loadMore(index: self.currIndex)
            }).disposed(by: disposeBag)
        collection.mj_header = header
        header.rx.refresh
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.page = 0
                self.loadMore(index: self.currIndex)
            }).disposed(by: disposeBag)
//        loadMore(index: 0)
        
        collection.rx.modelSelected(XS_discoverQuickLearnM.self)
            .asDriver()
            .drive(onNext: { item in
                let vc = XS_KuaiXueDetailVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        return view
    }
    
    func getTuijian() -> UIView {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        view.isHidden = true
        
        let bottomViewH = (.bottomHeight + 49)
        
        let bottomView = UIView()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(bottomViewH)
        }
        
        let flowLayout = UICollectionViewFlowLayout()
//        flowLayout.itemSize = view.bounds.size
        flowLayout.itemSize = CGSize.init(width: view.bounds.size.width, height: view.bounds.size.height - bottomViewH)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.contentInsetAdjustmentBehavior = .never
        collection.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        collection.bounces = false
        view.addSubview(collection)
//        collection.snp.makeConstraints {
//            $0.edges.equalToSuperview()
//        }
        collection.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-bottomViewH)
        }
        collection.isPagingEnabled = true
        collection.register(XS_TuijianCell.self, forCellWithReuseIdentifier: "cell")
        playerCollection = collection
        collection.delegate = self
        collection.dataSource = self
        
        AliPlayer.setEnableLog(false)
        
        return view
    }
}
extension XS_KuaiXueVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        playerData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == playerData.count-1 {
            loadMorePlayer()
        }
        let model = playerData[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XS_TuijianCell
        cell.modelPS.onNext(model)
        cell.loadUrl(model.videoUrl, isAutoPlay: player == nil)
        if player == nil { player = cell.player }
        return cell
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        player?.pause()
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        for cell in playerCollection.visibleCells {
            guard  UIScreen.main.bounds.contains(view.convert(cell.center, from: cell.superview)), let cell = cell as? XS_TuijianCell else {
                continue
            }
            player = cell.player
            player?.start()
            return
        }
    }
    
    func loadMorePlayer() {
        if XS_Singleton.shared.infoModel == nil, playerData.count > 10 {
            XS_NVC.shared.toLogin(true)
            return
        }
        XS_NetWork.requestJson("/quick/queryStar", parameters: ["count":5])
            .mapModels(type: XS_queryStarM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success, models.count > 0 else { return }
                let num = self.playerData.count
                self.playerData += models
                var items: [IndexPath] = []
                for index in 0..<models.count {
                    items.append(IndexPath(item: num+index, section: 0))
                }
                self.playerCollection.insertItems(at: items)
            }).disposed(by: disposeBag)
        
    }
}
extension XS_KuaiXueVC {
//    func getTag(_ text: String) -> UIView {
//        let view = UIView()
//        view.layer.cornerRadius = .scale*15
//        view.layer.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
//        let point = UIView()
//        point.layer.cornerRadius = .scale*1.5
//        point.layer.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
//        view.addSubview(point)
//        point.snp.makeConstraints({
//            $0.width.height.equalTo(.scale*3)
//            $0.centerY.equalToSuperview()
//            $0.left.equalTo(.scale*12)
//        })
//        let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: text)
//        view.addSubview(label)
//        label.snp.makeConstraints({
//            $0.left.equalTo(point.snp.right).offset(.scale*4)
//            $0.centerY.equalToSuperview()
//            $0.right.lessThanOrEqualTo(-.scale*11)
//        })
//        return view
//    }
    
    func getTag(_ text: String) -> UIButton {
        let btn = UIButton.init(type: .custom)
        btn.backgroundColor = .white
        btn.setTitle(text, for: .normal)
        btn.setTitleColor(UIColor(red: 0.60, green: 0.60, blue: 0.60, alpha: 1.00), for: .normal)
        btn.setTitleColor(UIColor(red: 0.22, green: 0.24, blue: 0.25, alpha: 1.00), for: .selected)
        btn.titleLabel?.font = btn.isSelected ? .systemFont(ofSize: .scale * 14, weight: .semibold) : .systemFont(ofSize: .scale * 14, weight: .regular)
        return btn
    }
    
    func getMenuitemQueryHomeTop() {
        self.channelArray.removeAll()
        let tmpModel = XS_HomeTopM()
        tmpModel.industryName = "热门视频"
        self.channelArray.append(tmpModel)
//        XS_NetWork.requestJson("/industry/queryAllStatusApi")
        XS_NetWork.requestJson("/industry/queryAllIndustryBySearchType", parameters: ["searchType" : "quickLearn"])
            .mapModels(type: XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
//                self.channelArray.append(contentsOf: models.filter({ $0.type != "nav" }))
                self.channelArray.append(contentsOf: models)
                self.reloadTop()
            }).disposed(by: disposeBag)
    }
    func reloadTop() {
        page = 0
        loadMore(index: 0)
//        topScroll.removeSubviews()
//        var last: UIView?
//        for item in channelArray {
//            let tag = getTag(item.name)
//            topScroll.addSubview(tag)
//            tag.snp.makeConstraints({
//                $0.height.equalTo(.scale*28)
//                $0.top.equalToSuperview()
//                $0.right.lessThanOrEqualToSuperview()
//                if let last = last {
//                    $0.left.equalTo(last.snp.right).offset(.scale*7)
//                } else {
//                    $0.left.equalTo(.scale*16)
//                }
//            })
//            last = tag
//        }
        for view in topScroll.subviews {
            if view.isKind(of: UIButton.self) {
                view.snp.removeConstraints()
                view.removeFromSuperview()
            }
        }
        var lastBtn: UIButton?
        for (index, item) in channelArray.enumerated() {
            let btn = getTag(item.industryName)
            btn.tag = index
            btn.addTarget(self, action: #selector(didScrollView(btn:)), for: .touchUpInside)
            topScroll.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
                make.height.equalTo(.scale * 29)
                if let last = lastBtn {
                    make.left.equalTo(last.snp.right).offset(.scale * 24)
                } else {
                    make.left.equalTo(.scale * 16)
                    btn.isSelected = true
                }
                if index == channelArray.count - 1 {
                    make.right.lessThanOrEqualTo(-.scale * 16)
                }
            }
            lastBtn = btn
        }
        didScrollView(to: 0)
    }
    
    @objc func didScrollView(btn: UIButton) {
        /// 点击同一个栏目不刷新
//        if btn.tag == self.currIndex {
//            return
//        }
        didScrollView(to: btn.tag)
        self.page = 0
        loadMore(index: self.currIndex)
    }
    
    func didScrollView(to btnIndex: Int) {
        self.currIndex = btnIndex
        for items in topScroll.subviews {
            if let item = items as? UIButton {
                if item.tag == btnIndex {
                    item.isSelected = true
                    UIView.animate(withDuration: 0.2) {
                        self.lineView.center.x = item.center.x
                        self.lineView.bounds.size.width = item.bounds.size.width
                        self.lineView.snp.remakeConstraints { (make) in
                            make.top.equalTo(.scale * 29)
                            make.height.equalTo(.scale * 3)
                            make.width.equalTo(item)
                            make.centerX.equalTo(item)
                        }
                    }
                } else {
                    item.isSelected = false
                }
            }
        }
    }
    
    func loadMore(index: Int) {
        guard XS_Singleton.shared.infoModel != nil else { return }
        if page == 0 {
            data.removeAll()
        }
        var param: [String : Any] = [:]
        
        if self.channelArray[index].industryName == "热门视频" {
            param = [
                "pageNo": (page + 1),
                "pageSize": 10
            ]
        } else {
            param = [
                "pageNo": (page + 1),
                "pageSize": 10,
                "industryId": self.channelArray[index].id
            ]
        }
        loadMoreDisposeBag = DisposeBag()
        XS_NetWork.requestJson("/quick/discoverQuickLearn", parameters: param)
            .mapModel(type: XS_ListM<XS_discoverQuickLearnM>.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.page += 1
                self.data += model.records
                self.dataPS.onNext(self.data)
                if model.current < model.pages {
                    self.footer.endRefreshing()
                } else {
                    self.footer.endRefreshingWithNoMoreData()
                }
                if self.data.count > 0 {
                    XD_BlankPageView.hiddenBlankPageView(superView: self.faxianCollection)
                } else {
                    XD_BlankPageView.blankPage(superView: self.faxianCollection, imgName: "缺省页_暂无内容", detailStr: "暂无内容~", bottomDetailStr: "")
                }
                self.header.endRefreshing()
            }).disposed(by: loadMoreDisposeBag)
    }
}

class XS_TuijianCell: XS_BaseCCell, AVPDelegate {
    lazy var modelPS = PublishSubject<XS_queryStarM>()
    var item: XS_queryStarM?
    lazy var player = AliPlayer()!
    lazy var slider = XS_VPSlider()
    
    deinit {
        player.destroy()
    }
    
    lazy var playBtn = getPlayBtn()
    func getPlayBtn() -> UIButton {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "icon_24px_播放_2"), for: .normal)
        btn.isHidden = true
        contentView.addSubview(btn)
        btn.snp.makeConstraints {
            $0.width.height.equalTo(.scale*80)
            $0.center.equalToSuperview()
        }
        btn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.player.start()
            }).disposed(by: disposeBag)
        return btn
    }
    
    override func upView() {
        let pImgV = UIImageView()
//        pImgV.backgroundColor = #colorLiteral(red: 0.1201849058, green: 0.1661828458, blue: 0.1523639858, alpha: 1)
        pImgV.contentMode = .scaleAspectFill
        pImgV.clipsToBounds = true
        contentView.addSubview(pImgV)
        pImgV.snp.makeConstraints { $0.edges.equalToSuperview() }
        let pView = UIView()
        pImgV.addSubview(pView)
        pView.snp.makeConstraints { $0.edges.equalToSuperview() }
        player.isLoop = true
        player.scalingMode = AVP_SCALINGMODE_SCALEASPECTFILL
        player.delegate = self
        player.playerView = pView
        
        let playTap = UITapGestureRecognizer()
        contentView.addGestureRecognizer(playTap)
        playTap.rx.event.asDriver()
            .drive(onNext: { [weak self] _ in
                self?.player.pause()
            }).disposed(by: disposeBag)
        
        slider.isUserInteractionEnabled = false
        contentView.addSubview(slider)
        slider.snp.makeConstraints({
            $0.left.right.equalToSuperview()
            $0.bottom.equalTo(-1)
        })
        
        /**
        do {
            let layerView = UIView()
            layerView.frame = CGRect(x: 0, y: .barHeight + 24, width: .scale*30, height: .scale*596)
            layerView.alpha = 1
            // fillCode
            let bglayer1 = CAGradientLayer()
            bglayer1.colors = [UIColor(red: 0.49, green: 0.91, blue: 0.91, alpha: 0.34).cgColor, UIColor(red: 0.27, green: 0.81, blue: 0.80, alpha: 1).cgColor]
            bglayer1.locations = [0, 1]
            bglayer1.frame = CGRect(x: 0, y: 0, width: .scale*70, height: .scale*596)
            layerView.layer.addSublayer(bglayer1)
            bglayer1.startPoint = CGPoint(x: 0.00, y: 0.51)
            bglayer1.endPoint = CGPoint(x: 1.00, y: 0.51)
            contentView.addSubview(layerView)
            
            let shapeLayer = CAShapeLayer()
            shapeLayer.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            bglayer1.mask = shapeLayer
            
            let y = .scale*596
            let path = UIBezierPath()
            path.move(to: .zero)
            path.addCurve(to: CGPoint(x: 0, y: y/2),
                          controlPoint1: CGPoint(x: 0, y: y/10),
                          controlPoint2: CGPoint(x: 0, y: y*3/10))
            path.addCurve(to: CGPoint(x: 0, y: y),
                          controlPoint1: CGPoint(x: 0, y: y*7/10),
                          controlPoint2: CGPoint(x: 0, y: y*9/10))
            path.addLine(to: .zero)
            shapeLayer.path = path.cgPath
            
            let imgV = UIImageView(image: UIImage(named: "icon_20_已掌握"))
            imgV.frame = CGRect(x: 0, y: 0, width: 20, height: 20) * .scale
            imgV.center = CGPoint(x: -.scale*17, y: y/2)
            layerView.addSubview(imgV)
            let label = UILabel.xsLabel(size: .scale*16, fontName: .semibold, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, lines: 3, text: "已\n掌\n握")
            label.frame = CGRect(x: 0, y: 0, width: 16, height: 70) * .scale
            label.center = CGPoint(x: -.scale*43, y: y/2)
            layerView.addSubview(label)
            
            let pan = UIPanGestureRecognizer()
            layerView.addGestureRecognizer(pan)
            pan.rx.event.asDriver()
                .drive(onNext: { [weak self] gesture in
                    let translation = gesture.translation(in: gesture.view)
                    let x = translation.x
                    switch gesture.state {
                    case .began:
                        let point = gesture.location(in: gesture.view)
                        if point.x > .scale*30 {
                            gesture.isEnabled = false
                            gesture.isEnabled = true
                        }
                    case .changed:
                        if x >= 0, x <= .scale*70 {
                            let path = UIBezierPath()
                            path.move(to: .zero)
                            path.addCurve(to: CGPoint(x: x, y: y/2),
                                          controlPoint1: CGPoint(x: 0, y: y/10),
                                          controlPoint2: CGPoint(x: x, y: y*3/10))
                            path.addCurve(to: CGPoint(x: 0, y: y),
                                          controlPoint1: CGPoint(x: x, y: y*7/10),
                                          controlPoint2: CGPoint(x: 0, y: y*9/10))
                            path.addLine(to: .zero)
                            shapeLayer.path = path.cgPath
                            
                            imgV.center.x = x - .scale*17
                            label.center.x = x - .scale*43
                        }
                    case .ended, .cancelled:
                        let path = UIBezierPath()
                        path.move(to: .zero)
                        path.addCurve(to: CGPoint(x: 0, y: y/2),
                                      controlPoint1: CGPoint(x: 0, y: y/10),
                                      controlPoint2: CGPoint(x: 0, y: y*3/10))
                        path.addCurve(to: CGPoint(x: 0, y: y),
                                      controlPoint1: CGPoint(x: 0, y: y*7/10),
                                      controlPoint2: CGPoint(x: 0, y: y*9/10))
                        path.addLine(to: .zero)
                        let ani = CAKeyframeAnimation.getAnimation(.path)
                        ani.values = [shapeLayer.path!, path.cgPath]
                        ani.duration = 0.125
                        shapeLayer.path = path.cgPath
                        shapeLayer.add(ani, forKey: nil)
                        UIView.animate(withDuration: 0.125) {
                            imgV.center.x = -.scale*17
                            label.center.x = -.scale*43
                        }
                        if x > .scale*60, let id = self?.item?.id {
                            _ = XS_NetWork.requestJson("/quick/tagQuickLearn", parameters: ["state":"learned", "quickLearnId":id])
                                .subscribe(onNext: { resp in
                                    xsWindow()?.xsShowMsg(resp.success ? "操作成功" :"操作失败")
                                })
                        }
                    default: break
                    }
                }).disposed(by: disposeBag)
        }
        
        do {
            let layerView = UIView()
            layerView.frame = CGRect(x: .scale*345, y: .barHeight + 24, width: .scale*30, height: .scale*596)
            layerView.alpha = 1
            // fillCode
            let bglayer1 = CAGradientLayer()
            bglayer1.colors = [UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 0.34).cgColor, UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1).cgColor]
            bglayer1.locations = [0, 1]
            bglayer1.frame = CGRect(x: -.scale*40, y: 0, width: .scale*70, height: .scale*596)
            layerView.layer.addSublayer(bglayer1)
            bglayer1.startPoint = CGPoint(x: 0.96, y: 0.51)
            bglayer1.endPoint = CGPoint(x: 0.00, y: 0.51)
            contentView.addSubview(layerView)
            
            let shapeLayer = CAShapeLayer()
            shapeLayer.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            bglayer1.mask = shapeLayer
            
            let y = .scale*596
            let path = UIBezierPath()
            path.move(to: CGPoint(x: .scale*70, y: 0))
            path.addCurve(to: CGPoint(x: .scale*70, y: y/2),
                          controlPoint1: CGPoint(x: .scale*70, y: y/10),
                          controlPoint2: CGPoint(x: .scale*70, y: y*3/10))
            path.addCurve(to: CGPoint(x: .scale*70, y: y),
                          controlPoint1: CGPoint(x: .scale*70, y: y*7/10),
                          controlPoint2: CGPoint(x: .scale*70, y: y*9/10))
            path.addLine(to: CGPoint(x: .scale*70, y: 0))
            shapeLayer.path = path.cgPath
            
            let imgV = UIImageView(image: UIImage(named: "icon_20_未记住"))
            imgV.frame = CGRect(x: 0, y: 0, width: 20, height: 20) * .scale
            imgV.center = CGPoint(x: .scale*47, y: y/2)
            layerView.addSubview(imgV)
            let label = UILabel.xsLabel(size: .scale*16, fontName: .semibold, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, lines: 3, text: "未\n记\n住")
            label.frame = CGRect(x: 0, y: 0, width: 16, height: 70) * .scale
            label.center = CGPoint(x: .scale*73, y: y/2)
            layerView.addSubview(label)
            
            let pan = UIPanGestureRecognizer()
            layerView.addGestureRecognizer(pan)
            pan.rx.event.asDriver()
                .drive(onNext: { [weak self] gesture in
                    let translation = gesture.translation(in: gesture.view)
                    let x = -translation.x
                    switch gesture.state {
                    case .began:
                        break
                    case .changed:
                        if x >= 0, x <= .scale*70 {
                            let path = UIBezierPath()
                            path.move(to: CGPoint(x: .scale*70, y: 0))
                            path.addCurve(to: CGPoint(x: .scale*70-x, y: y/2),
                                          controlPoint1: CGPoint(x: .scale*70, y: y/10),
                                          controlPoint2: CGPoint(x: .scale*70-x, y: y*3/10))
                            path.addCurve(to: CGPoint(x: .scale*70, y: y),
                                          controlPoint1: CGPoint(x: .scale*70-x, y: y*7/10),
                                          controlPoint2: CGPoint(x: .scale*70, y: y*9/10))
                            path.addLine(to: CGPoint(x: .scale*70, y: 0))
                            shapeLayer.path = path.cgPath
                            
                            imgV.center.x = .scale*47 - x
                            label.center.x = .scale*73 - x
                        }
                    case .ended, .cancelled:
                        let path = UIBezierPath()
                        path.move(to: CGPoint(x: .scale*70, y: 0))
                        path.addCurve(to: CGPoint(x: .scale*70, y: y/2),
                                      controlPoint1: CGPoint(x: .scale*70, y: y/10),
                                      controlPoint2: CGPoint(x: .scale*70, y: y*3/10))
                        path.addCurve(to: CGPoint(x: .scale*70, y: y),
                                      controlPoint1: CGPoint(x: .scale*70, y: y*7/10),
                                      controlPoint2: CGPoint(x: .scale*70, y: y*9/10))
                        path.addLine(to: CGPoint(x: .scale*70, y: 0))
                        let ani = CAKeyframeAnimation.getAnimation(.path)
                        ani.values = [shapeLayer.path!, path.cgPath]
                        ani.duration = 0.125
                        shapeLayer.path = path.cgPath
                        shapeLayer.add(ani, forKey: nil)
                        UIView.animate(withDuration: 0.125) {
                            imgV.center.x = .scale*47
                            label.center.x = .scale*73
                        }
                        if x > .scale*60, let id = self?.item?.id {
                            _ = XS_NetWork.requestJson("/quick/tagQuickLearn", parameters: ["state":"unlearned", "quickLearnId":id])
                                .subscribe(onNext: { resp in
                                    xsWindow()?.xsShowMsg(resp.success ? "操作成功" :"操作失败")
                                })
                        }
                    default: break
                    }
                }).disposed(by: disposeBag)
        }
        */
        
        let bottomLayerView = UIView()
        bottomLayerView.frame = CGRect(x: 0, y: contentView.bounds.size.height - .scale * 200, width: contentView.bounds.size.width, height: .scale * 200)
        bottomLayerView.alpha = 1
//        bottomLayerView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        // fillCode
        let bottomBgLayer = CAGradientLayer()
//        bottomBgLayer.colors = [UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 0.00).cgColor, UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 0.40).cgColor]
        bottomBgLayer.colors = [UIColor.black.withAlphaComponent(0).cgColor, UIColor.black.withAlphaComponent(0.5).cgColor]
        bottomBgLayer.locations = [0, 1]
        bottomBgLayer.frame = bottomLayerView.bounds
        bottomLayerView.layer.insertSublayer(bottomBgLayer, at: 0)
        contentView.addSubview(bottomLayerView)
        
        let titleLab = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: .white, text: "标题")
        //阴影颜色
        titleLab.layer.shadowColor = UIColor(red: 0.47, green: 0.47, blue: 0.47, alpha: 1.00).cgColor
        //阴影偏移  x，y为正表示向右下偏移
        titleLab.layer.shadowOffset = CGSize.init(width: 1, height: 1)
        titleLab.layer.shadowOpacity = 0.5
        contentView.addSubview(titleLab)
        titleLab.snp.makeConstraints({
            $0.bottom.equalTo(-.scale*75)
            $0.left.equalTo(.scale*16)
            $0.width.lessThanOrEqualTo(.scale*253)
        })
        let descLab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: .white, lines: 2)
        //阴影颜色
        descLab.layer.shadowColor = UIColor(red: 0.47, green: 0.47, blue: 0.47, alpha: 1.00).cgColor
        //阴影偏移  x，y为正表示向右下偏移
        descLab.layer.shadowOffset = CGSize.init(width: 1, height: 1)
        descLab.layer.shadowOpacity = 0.5
        contentView.addSubview(descLab)
        descLab.snp.makeConstraints({
            $0.top.equalTo(titleLab.snp.bottom).offset(.scale*4)
            $0.left.equalTo(.scale*16)
            $0.width.lessThanOrEqualTo(.scale*253)
        })
        
        let btn = XS_Button()
        btn.setBackgroundImage(UIImage(named: "icon_64_收藏_绿_2"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "icon_64_收藏_绿"), for: .selected)
        contentView.addSubview(btn)
        btn.snp.makeConstraints({
            $0.width.height.equalTo(.scale*32)
            $0.right.equalTo(-.scale*16)
//            $0.bottom.equalTo(-.scale*117 - 49 - .bottomHeight)
        })
        let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: .white, alignment: .center, text: "收藏")
        //阴影偏移  x，y为正表示向右下偏移
        label.layer.shadowOffset = CGSize.init(width: 1, height: 1)
        label.layer.shadowOpacity = 0.5
        btn.addSubview(label)
        label.snp.makeConstraints({
            $0.centerX.equalToSuperview()
            $0.top.equalTo(btn.snp.bottom)
//            $0.bottom.equalTo(descLab)
            $0.bottom.equalTo(titleLab.snp.top).offset(-.scale * 4)
        })
        
        let view = UIView()
        view.isHidden = true
        contentView.addSubview(view)
        view.snp.makeConstraints({
            $0.width.equalTo(.scale*237)
            $0.height.equalTo(.scale*75)
            $0.left.equalTo(.scale*16)
//            $0.bottom.equalTo(-.scale*19 - 49 - .bottomHeight)
            $0.bottom.equalTo(titleLab.snp.top).offset(-.scale * 4)
        })
        
        let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
        effectView.layer.cornerRadius = .scale*8
        effectView.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.25)
        effectView.layer.borderWidth = 1
        effectView.layer.borderColor = #colorLiteral(red: 0.5921568627, green: 0.5921568627, blue: 0.5921568627, alpha: 0.1)
        effectView.layer.masksToBounds = true
        effectView.alpha = 0.25
        view.addSubview(effectView)
        effectView.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        
        let cImgV = UIImageView()
        view.addSubview(cImgV)
        cImgV.snp.makeConstraints({
            $0.left.equalTo(.scale*8)
            $0.width.equalTo(.scale*81)
            $0.height.equalTo(.scale*59)
            $0.centerY.equalToSuperview()
        })
        let cLab = UILabel.xsLabel(size: .scale*13, fontName: .semibold, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), lines: 2)
        view.addSubview(cLab)
        cLab.snp.makeConstraints({
            $0.left.equalTo(cImgV.snp.right).offset(.scale*12)
            $0.top.equalTo(.scale*8)
            $0.width.lessThanOrEqualTo(.scale*104)
        })
        let cPrice = UILabel.xsLabel(size: .scale*13, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1))
        view.addSubview(cPrice)
        cPrice.snp.makeConstraints({
            $0.left.equalTo(cImgV.snp.right).offset(.scale*12)
            $0.bottom.equalTo(-.scale*9)
        })
        let cClose = XS_Button()
        cClose.setBackgroundImage(UIImage(named: "icon_16_关闭"), for: .normal)
        view.addSubview(cClose)
        cClose.snp.makeConstraints({
            $0.width.height.equalTo(.scale*20)
            $0.top.equalTo(.scale*5)
            $0.right.equalTo(-.scale*7)
        })
        cClose.rx.tap.asDriver()
            .drive(onNext: {
                view.isHidden = true
            }).disposed(by: disposeBag)
        
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { [weak self] _ in
                guard let `self` = self, let item = self.item else { return }
                switch item.curriculumDto.curriculumForm {
                case "online":
                    let vc = XS_KeChengVC()
                    vc.id = "\(item.curriculumDto.id)"
                    XS_NVC.shared.pushViewController(vc, animated: true)
                case "offline":
                    let vc = XS_KCXianxiaVC()
                    vc.id = "\(item.curriculumDto.id)"
                    XS_NVC.shared.pushViewController(vc, animated: true)
                default:
                    break
                }
            }).disposed(by: disposeBag)
        
        modelPS.subscribe(onNext: { [weak self] item in
            self?.item = item
            self?.playBtn.isHidden = true
            titleLab.text = item.title
            descLab.text = item.description
            btn.isSelected = item.isCollect == "yes"
            if item.curriculumDto.id > 0 {
                let (p, _) = xsGetPrice(vipIsFree: "", isFree: "", vipPrice: "", discountPrice: item.curriculumDto.discountPrice, price: item.curriculumDto.price)
                cImgV.sd_setImage(with: URL(string: item.curriculumDto.curriculumImgUrl))
                cLab.text = item.curriculumDto.curriculumName
                cPrice.text = p.count > 0 ? "¥ \(p)" : "免费"
                view.isHidden = false
            } else {
                view.isHidden = true
            }
            pImgV.sd_setImage(with: URL(string: item.imgUrl), placeholderImage: UIImage(named: "编组快学推荐"))
        }).disposed(by: disposeBag)
        
        btn.rx.tap.asDriver()
            .throttle(.milliseconds(500), latest: false)
            .drive(onNext: { [weak self] in
                guard let item = self?.item else { return }
                if item.isCollect == "yes" {
                    item.isCollect = "no"
                    _ = XS_NetWork.requestJson("/collection/collectionCancel", parameters: ["relation":item.id,"type":"quick"])
                        .subscribe()
                } else {
                    item.isCollect = "yes"
                    _ = XS_NetWork.requestJson("/collection/collectionButton", parameters: ["relation":item.id,"type":"quick"])
                        .subscribe()
                }
//                self?.modelPS.onNext(item)
                btn.isSelected = item.isCollect == "yes"
            }).disposed(by: disposeBag)
    }
    
    func loadUrl(_ urlStr: String, isAutoPlay: Bool) {
        player.playerView.isHidden = true
        player.isAutoPlay = isAutoPlay
        let dataSource = AVPUrlSource()
        dataSource.url(with: urlStr)
        player.setUrlSource(dataSource)
        player.prepare()
    }
    
    func onPlayerStatusChanged(_ player: AliPlayer!, oldStatus: AVPStatus, newStatus: AVPStatus) {
        switch newStatus {
        case .init(2): // 准备完成
            player.seek(toTime: 0, seekMode: .init(1))
            slider.upSlider(player.currentPosition, total: player.duration)
        case .init(3):
            playBtn.isHidden = true
            player.playerView.isHidden = false
        case .init(4):
            playBtn.isHidden = false
            playBtn.superview?.bringSubviewToFront(playBtn)
//        case .init(6): // 播放完成
//            UIView.animate(withDuration: 0.5) { self.consoleView.alpha = 1 }
        default:
            break
        }
    }
    func onCurrentPositionUpdate(_ player: AliPlayer!, position: Int64) {
        slider.upSlider(position, total: player.duration)
    }
    func onBufferedPositionUpdate(_ player: AliPlayer!, position: Int64) {
        slider.upSliderLoading(Float(position)/Float(player.duration))
    }
}

class XS_FaxianCell: XS_BaseCCell {
    lazy var modelPS = PublishSubject<XS_discoverQuickLearnM>()
    var item: XS_discoverQuickLearnM?
    override func upView() {
        contentView.layer.cornerRadius = .scale*4
        contentView.layer.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.layer.masksToBounds = true
        
        let imgV = UIImageView()
        imgV.backgroundColor = .black
        imgV.contentMode = .scaleAspectFit
        imgV.layer.transform = CATransform3DMakeScale(1.02, 1.02, 1.0)
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            $0.height.equalTo(.scale * 166 * (1280 / 720))
        })
        let bgView = UIView()
        bgView.backgroundColor = UIColor(red: 0.03, green: 0, blue: 0, alpha: 0.49)
        contentView.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(.scale * 63)
        }
        
        let titleLab = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: .white, text: "标题标题标题标…")
        bgView.addSubview(titleLab)
        titleLab.snp.makeConstraints({
            $0.top.left.equalTo(.scale * 12)
            $0.right.equalTo(-.scale * 12)
        })
        let peopleLab = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: .white, text: "242人加入学习")
        bgView.addSubview(peopleLab)
        peopleLab.snp.makeConstraints({
            $0.top.equalTo(titleLab.snp.bottom).offset(.scale*2)
            $0.left.right.equalTo(titleLab)
            $0.height.equalTo(.scale * 17)
            $0.bottom.equalTo(-.scale * 12)
        })
        let btn = XS_Button()
        btn.layer.backgroundColor = UIColor(red: 0.03, green: 0, blue: 0, alpha: 0.49).cgColor
//        btn.setImage(UIImage(named: "icon_64_收藏_绿_1"), for: .normal)
//        btn.setImage(UIImage(named: "icon_64_收藏_绿"), for: .selected)
        btn.setImage(UIImage(named: "icon_24px_收藏_1"), for: .normal)
        btn.setImage(UIImage(named: "icon_24px_收藏备份"), for: .selected)
        btn.imageEdgeInsets = UIEdgeInsets.init(top: .scale * 8, left: 0, bottom: .scale * 8, right: 0)
        btn.imageView!.contentMode = .scaleAspectFit
        btn.setTitle("收藏", for: .normal)
        btn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .regular, .scale*11)
        contentView.addSubview(btn)
        btn.snp.makeConstraints({
            $0.width.equalTo(.scale*62)
            $0.height.equalTo(.scale*28)
            $0.top.right.equalToSuperview()
        })
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 62, height: 28) * .scale, byRoundingCorners: .bottomLeft, cornerRadii: CGSize(width: 8, height: 8) * .scale).cgPath
        btn.layer.mask = shapeLayer
        
        modelPS.subscribe(onNext: { [weak self] item in
            self?.item = item
            imgV.sd_setImage(with: URL(string: item.imgUrl))
            titleLab.text = item.title
            peopleLab.text = "\(item.collectCount)人已收藏"
            btn.isSelected = item.isCollect == "yes"
        }).disposed(by: disposeBag)
        
        btn.rx.tap.asDriver()
            .throttle(.milliseconds(500), latest: false)
            .drive(onNext: { [weak self] in
                guard let item = self?.item else { return }
                if item.isCollect == "yes" {
                    item.isCollect = "no"
                    item.collectCount -= 1
                    _ = XS_NetWork.requestJson("/collection/collectionCancel", parameters: ["relation":item.id,"type":"quick"])
                        .subscribe()
                } else {
                    item.isCollect = "yes"
                    item.collectCount += 1
                    _ = XS_NetWork.requestJson("/collection/collectionButton", parameters: ["relation":item.id,"type":"quick"])
                        .subscribe()
                }
                self?.modelPS.onNext(item)
            }).disposed(by: disposeBag)
    }
}
